package edu.hawaii.ics414;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class CalendarListActivity extends Activity {
  private ListView list;
  private String[] sArray;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.calendarlist);
    StrictMode.enableDefaults();
    list = (ListView) findViewById(R.id.listView1);
    Intent intent = getIntent();
    CalendarList events = intent.getParcelableExtra("calendar");
    displayEvents(events);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
  }
  
  private void displayEvents(final CalendarList events) {
    try {
      sArray = events.getTitles();
      ArrayAdapter<String> adapter =
          new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sArray);
      list.setAdapter(adapter);
      list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
          Intent intent = new Intent("edu.hawaii.ics414.DETAILS");
          Bundle b = new Bundle();
          try {
            b.putString("title", events.getEvent(position).get("title"));
            b.putString("description", events.getEvent(position).get("description"));
            b.putString("date", events.getEvent(position).get("date"));
            b.putString("venue", events.getEvent(position).get("venue"));
          }
          catch (Exception e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
          }
          intent.putExtras(b);
          startActivity(intent);
        }
      });

    }
    catch (Exception e) {
      Log.e("log_tag", "Error parsing data " + e.toString());
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    super.onOptionsItemSelected(item);

    switch (item.getItemId()) {
    case R.id.home:
      finish();
      break;

    case R.id.calendar:
      Intent calendar = new Intent(getApplicationContext(), CalendarActivity.class);
      finish();
      startActivity(calendar);
      break;

    /*
     * case R.id.nearbyevents: Intent nearbyevents = new Intent(getApplicationContext(),
     * NearbyEventsActivity.class); finish(); startActivity(nearbyevents); break;
     * 
     * case R.id.info: Intent info = new Intent(getApplicationContext(), InfoActivity.class);
     * finish(); startActivity(info); break;
     */

    }
    return true;
  }
}
